package com.youdoneed.friends.coolface;

import com.querydsl.sql.SQLQuery;
import com.querydsl.sql.SQLQueryFactory;
import com.youdoneed.base.application.AppException;
import com.youdoneed.base.common.GlobalIdWorker;
import com.youdoneed.friends.model.HasCheckCoolFace;
import com.youdoneed.friends.query.QHasCheckCoolFace;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class HasCheckCoolFaceService {

    private final Logger logger = LoggerFactory.getLogger(HasCheckCoolFaceService.class);

    @Autowired
    private SQLQueryFactory queryFactory;
    private QHasCheckCoolFace qHasCheckCoolFace = QHasCheckCoolFace.HasCheckCoolFace;

    public List<HasCheckCoolFace> findHasCheckCoolFaceList(String userId, String searchId) {
        if (!StringUtils.hasText(userId)) {
            throw new AppException("用户ID不能为空");
        }
        SQLQuery<HasCheckCoolFace> query = queryFactory.selectFrom(qHasCheckCoolFace)
                .where(qHasCheckCoolFace.userId.eq(userId));
        if (StringUtils.hasText(searchId)) {
            query.where(qHasCheckCoolFace.searchId.eq(searchId));
        }
        return query.fetch();
    }

    public long saveHasCheckCoolFace(String userId, String searchId) {
        if (!StringUtils.hasText(userId)) {
            throw new AppException("用户ID不能为空");
        }
        if (!StringUtils.hasText(searchId)) {
            throw new AppException("搜索ID不能为空");
        }
        if (findHasCheckCoolFaceList(userId, searchId).size() > 0) {
            return 0L;
        }
        return queryFactory.insert(qHasCheckCoolFace)
                .set(qHasCheckCoolFace.hasCheckCoolfaceId, GlobalIdWorker.nextString())
                .set(qHasCheckCoolFace.userId, userId)
                .set(qHasCheckCoolFace.searchId, searchId)
                .set(qHasCheckCoolFace.createTime, new Date())
                .execute();
    }

}
